package lion.framework.core.db;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lion.dev.exception.DBException;
import lion.dev.lang.MapJ;

/**
 * 编译解析命名式sql
 *
 * <pre>
 * time   2013 2013-4-24 上午11:28:41
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class NamedSQL {

	private static final Pattern pattern = Pattern.compile(":(\\w+)");
	private String origSQL;
	private MapJ param;
	private String sql;

	private List<Object> paramValues = new ArrayList<>();

	public NamedSQL(String sql, MapJ param) {

		origSQL = sql;
		this.param = param;
		if (this.param == null) {
			this.param = new MapJ();
		}
	}

	public static boolean isNamedSQL(String sql) {

		Matcher m = pattern.matcher(sql);

		return m.find();
	}

	public Object[] getParameterValues() {

		return paramValues.toArray();
	}

	public String preparedSQL() {

		substuiteParameters();

		return sql;
	}

	private void substuiteParameters() {

		Matcher m = pattern.matcher(origSQL);
		StringBuffer sbu = new StringBuffer();
		while (m.find()) {
			String key = m.group(1);

			if (!param.containsKey(key)) { throw new DBException(String.format("no value for the parameter %s has been set. [%s]", key, origSQL)); }

			m.appendReplacement(sbu, "?");
			paramValues.add(param.get(key));
		}
		m.appendTail(sbu);

		sql = sbu.toString();
	}

}
